<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <div class="logo">
          <el-icon><ShoppingBag /></el-icon>
          <span class="logo-text">AI商城</span>
        </div>
        <h2 class="register-title">用户注册</h2>
        <p class="register-subtitle">创建您的AI商城账号，享受便捷购物体验</p>
      </div>
      
      <el-form 
        ref="registerFormRef" 
        :model="registerForm" 
        :rules="registerRules" 
        class="register-form"
      >
        <el-form-item prop="phone">
          <el-input 
            v-model="registerForm.phone" 
            placeholder="请输入手机号码"
            :prefix-icon="Phone"
            clearable
            maxlength="11"
            :validate-event="false"
          />
        </el-form-item>
        
        <el-form-item prop="verificationCode">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input 
                v-model="registerForm.verificationCode" 
                placeholder="请输入验证码"
                :prefix-icon="Message"
                clearable
                maxlength="6"
                :validate-event="false"
              />
            </el-col>
            <el-col :span="8">
              <el-button 
                type="primary" 
                plain
                :disabled="countdown > 0"
                @click="sendVerificationCode"
                class="verification-btn"
              >
                {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请设置密码（6-20位字母、数字或符号组合）"
            :prefix-icon="Lock"
            :show-password="showPassword"
            :validate-event="false"
          >
            <template #suffix>
              <i 
                class="el-icon-view" 
                @click="showPassword = !showPassword"
                :class="{ 'el-icon-view-close': showPassword }"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            :prefix-icon="Lock"
            :show-password="showConfirmPassword"
            :validate-event="false"
          >
            <template #suffix>
              <i 
                class="el-icon-view" 
                @click="showConfirmPassword = !showConfirmPassword"
                :class="{ 'el-icon-view-close': showConfirmPassword }"
              ></i>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="registerForm.agreeTerms">
            我已阅读并同意 <el-link type="primary">《用户协议》</el-link>和<el-link type="primary">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleRegister"
            :loading="loading"
            class="register-btn"
          >
            立即注册
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-entry">
        已有账号？
        <el-link type="primary" @click="goToLogin">立即登录</el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Phone, Message, Lock, ShoppingBag } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { userAPI } from '../../api/user'

const router = useRouter()
const registerFormRef = ref(null)
const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const countdown = ref(0)
let timer = null

// 注册表单数据
const registerForm = reactive({
  phone: '',
  verificationCode: '',
  password: '',
  confirmPassword: '',
  agreeTerms: false
})

// 注册表单验证规则
const registerRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' },
    { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_@./#&+-]{6,20}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  agreeTerms: [
    { validator: (rule, value, callback) => {
      if (!value) {
        callback(new Error('请阅读并同意用户协议和隐私政策'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ]
}

// 发送验证码
const sendVerificationCode = async () => {
  // 验证手机号
  const phoneRule = registerRules.phone
  for (const rule of phoneRule) {
    if (rule.required && !registerForm.phone) {
      ElMessage.error(rule.message)
      return
    }
    if (rule.pattern && !rule.pattern.test(registerForm.phone)) {
      ElMessage.error(rule.message)
      return
    }
  }
  
  try {
    // 模拟发送验证码
    // 实际项目中应调用 userAPI.sendVerificationCode(registerForm.phone)
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('验证码发送成功')
    
    // 开始倒计时
    startCountdown()
  } catch (error) {
    ElMessage.error('验证码发送失败，请稍后重试')
    console.error('发送验证码失败:', error)
  }
}

// 倒计时函数
const startCountdown = () => {
  countdown.value = 60
  
  if (timer) {
    clearInterval(timer)
  }
  
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 处理注册
const handleRegister = async () => {
  // 表单验证
  try {
    await registerFormRef.value.validate()
  } catch (error) {
    return
  }
  
  loading.value = true
  try {
    // 模拟注册请求
    // 实际项目中应调用 userAPI.register(registerForm)
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    ElMessage.success('注册成功，即将跳转到登录页面')
    
    // 注册成功后跳转到登录页
    setTimeout(() => {
      router.push({
        path: '/login',
        query: { phone: registerForm.phone }
      })
    }, 1000)
  } catch (error) {
    ElMessage.error('注册失败：' + (error.message || '网络异常，请稍后重试'))
    console.error('注册失败:', error)
  } finally {
    loading.value = false
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: $bg-color;
  background-image: 
    linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

/* 注册卡片 */
.register-card {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-lg;
  width: 100%;
  max-width: 400px;
  padding: 40px;
  box-sizing: border-box;
}

/* 注册头部 */
.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.logo .el-icon {
  font-size: 36px;
  color: $primary-color;
  margin-right: 10px;
}

.logo-text {
  font-size: $font-size-xl;
  color: $primary-color;
  font-weight: bold;
}

.register-title {
  font-size: $font-size-xl;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 10px;
}

.register-subtitle {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin: 0;
}

/* 注册表单 */
.register-form {
  width: 100%;
}

.register-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.register-form :deep(.el-input__wrapper) {
  border-radius: $border-radius-base;
  height: 40px;
}

.register-form :deep(.el-input__inner) {
  border-radius: $border-radius-base;
  height: 40px;
  line-height: 40px;
}

.verification-btn {
  width: 100%;
  height: 40px;
}

.register-btn {
  width: 100%;
  height: 40px;
  font-size: $font-size-base;
}

/* 登录入口 */
.login-entry {
  text-align: center;
  margin-top: 20px;
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-card {
    padding: 30px 20px;
    margin: 20px 0;
  }
  
  .logo .el-icon {
    font-size: 30px;
  }
  
  .logo-text {
    font-size: $font-size-lg;
  }
  
  .register-title {
    font-size: $font-size-lg;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 10px;
  }
  
  .register-card {
    padding: 20px 15px;
  }
}
</style>